<template>
	<view class="container">
		<!-- 顶部区域信息卡片 -->
		<bus-card
			size="large"
			title="区域信息"
			v-for="(item, index) in deviceDataSource"
			:key="index"
		>
			<template slot="cardBody">
				<uni-row>
					<uni-col :span="16">
						<bus-card-item
							:showCount="3"
							:columns="deviceColumns"
							:data="item"
						></bus-card-item>
					</uni-col>
					<uni-col :span="8">
						<image
							v-if="formData.orderStatus === '待执行'"
							class="excetImage"
							src="/static/exect.png"
							mode="aspectFill"
						/>
						<order-tag
							v-else
							:orderStatus="formData.orderStatus"
						></order-tag>
					</uni-col>
				</uni-row>
			</template>
		</bus-card>

		<!-- 执行数量展示 -->
		<view class="mid-content">
			<view class="left">
				<view>执行数量:{{ executedNum }}/{{ executeTotalNum }}</view>
			</view>
		</view>

		<!-- 项目列表 -->
		<scroll-view class="scroll-view" scroll-y="true">
			<view class="project-list">
				<view
					v-for="(project, projectIndex) in dataSource"
					:key="projectIndex"
					class="project-item"
					@click.stop="handlerExecute(project)"
				>
					<!-- 项目头部 -->
					<view class="project-header">
						<view class="project-info">
							<view class="project-title">
								<view class="project-icon"></view>
								<view>{{ project.groupName }}</view>
							</view>
							<view class="project-code"
								>项目编码：{{ project.planCode }}</view
							>
							<view class="project-code"
								>项目名称：{{ project.groupName }}</view
							>
						</view>
						<view class="project-status">
							<button
								class="status-button"
								@click.stop="handlerExecute(project)"
							>
								{{ project.status }}
							</button>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 底部按钮 -->
		<view class="bottom-btn" v-if="false">
			<button
				:loading="btnLoading"
				:disabled="btnLoading"
				size="mini"
				type="default"
				@click="handleStore"
			>
				暂存
			</button>
			<button
				:loading="btnLoading"
				:disabled="btnLoading"
				size="mini"
				type="primary"
				@click="handleSubmit"
			>
				提交
			</button>
		</view>

		<!-- 空状态 -->
		<view v-if="dataSource.length === 0">
			<empty-block></empty-block>
		</view>
	</view>
</template>

<script>
import {
	checkDetail,
	checkTemporaryStorage,
	checkSubmit,
} from '@/api/check.js';
export default {
	name: '',
	data() {
		return {
			activeIndex: -1,
			dataSource: [],
			deviceDataSource: [],
			formData: {},
			btnLoading: false,
			executedNum: 0,
			executeTotalNum: 0,
		};
	},
	computed: {
		deviceColumns() {
			return [
				{ label: '区域编码', prop: 'areaCode' },
				{ label: '区域名称', prop: 'areaName' },
				{ label: '计划执行日期', prop: 'startDate' },
			];
		},
	},
	onLoad(option) {
		this.formData = JSON.parse(option.data);
		this.deviceDataSource = [this.formData];
		this.getList();
	},
	onShow() {},
	methods: {
		formatStandardValue(value) {
			// 检查是否为0（包含字符串'0'）
			if (value === 0 || value === '0') return 0;

			// 处理其他值
			return value || '-';
		},
		// 展开/收起项目
		toggleExpand(index) {
			this.activeIndex = this.activeIndex === index ? -1 : index;
		},

		// 更新实测值
		updateMeasureValue(projectIndex, detailIndex, event) {
			const value = event.detail.value;

			// 使用Vue的set方法确保响应式更新
			this.$set(
				this.dataSource[projectIndex].detailList[detailIndex],
				'measureValue',
				value,
			);

			// 检查输入值并更新项目状态
			if (value.trim() !== '') {
				this.checkAndUpdateProjectStatus(projectIndex);
			}
		},

		// 检查并更新项目状态
		checkAndUpdateProjectStatus(projectIndex) {
			const project = this.dataSource[projectIndex];
			const completedCount = project.detailList.filter(
				(detail) => detail.measureValue?.trim() !== '',
			).length;

			// 如果需要，可以在这里更新项目状态
			// 例如：project.status = completedCount === project.detailList.length ? 'completed' : 'pending';

			// 更新已执行数量统计
			this.executedNum = this.dataSource.reduce((total, proj) => {
				return (
					total +
					proj.detailList.filter(
						(detail) => detail.measureValue?.trim() !== '',
					).length
				);
			}, 0);
		},

		// 处理拍照
		handlePhoto(detail, projectIndex, detailIndex) {
			console.log('detail', detail);
			uni.navigateTo({
				url:
					'/pages/jdCheck/addPhoto/index?data=' +
					JSON.stringify({
						...detail,
						projectIndex,
						detailIndex,
					}),
				events: {
					addPhotoOk: (params) => {
						const { fileList } = params;

						// 使用Vue的set方法确保响应式更新
						this.$set(
							this.dataSource[projectIndex].detailList[
								detailIndex
							],
							'fileList',
							fileList,
						);
					},
				},
			});
		},

		// 获取数据
		async getList() {
			const userInfor = uni.getStorageSync('userInfor');
			const res = await checkDetail({
				startDate: this.formData.startDate,
				endDate: this.formData.endDate,
				areaId: this.formData.areaId,
				type: this.formData.type,
				cycleType: this.formData.cycleType,
				userNumber: userInfor.number,
			});
			const { data } = res || {};
			this.dataSource = data.children || [];
			this.executedNum = data?.num || 0;
			this.executeTotalNum = data?.total || 0;
		},

		// 暂存
		async handleStore() {
			this.btnLoading = true;
			try {
				const res = await checkTemporaryStorage(
					this.dataSource.map((project) => ({
						...project,
						detailList: project.detailList.map((detail) => ({
							...detail,
							fileList: detail.fileList || [],
						})),
					})),
				);

				if (res.code === 200) {
					uni.showToast({ title: '暂存成功', icon: 'success' });
					this.back();
				} else {
					uni.showToast({
						title: res.message || '暂存失败',
						icon: 'none',
					});
				}
			} catch (error) {
				uni.showToast({ title: '请求失败，请重试', icon: 'none' });
			} finally {
				this.btnLoading = false;
			}
		},

		handlerExecute(row) {
			this.formDisabled = false;
			const tempData = {
				...row,
				...this.formData,
			};
			uni.navigateTo({
				url:
					'/pages/jdCheck/execute/index?data=' +
					JSON.stringify(tempData),
			});
		},
		// 提交
		async handleSubmit() {
			// 验证所有必填项
			const hasError = this.dataSource.some((project) =>
				project.detailList.some(
					(detail) =>
						detail.measureValue?.trim() === '' ||
						!detail.fileList ||
						detail.fileList.length === 0,
				),
			);

			if (hasError) {
				uni.showToast({
					title: '实测值或拍照未填',
					icon: 'error',
				});
				return;
			}

			this.btnLoading = true;
			try {
				const res = await checkSubmit(
					this.dataSource.map((project) => ({
						...project,
						detailList: project.detailList.map((detail) => ({
							...detail,
							fileList: detail.fileList || [],
						})),
					})),
				);

				if (res.code === 200) {
					uni.showToast({ title: '提交成功', icon: 'success' });
					this.back();
				} else {
					uni.showToast({
						title: res.message || '提交失败',
						icon: 'none',
					});
				}
			} catch (error) {
				uni.showToast({ title: '提交失败，请重试', icon: 'none' });
			} finally {
				this.btnLoading = false;
			}
		},

		// 返回上一页
		back() {
			setTimeout(() => {
				this.btnLoading = false;
				uni.navigateBack();
			}, 1500);
		},
	},
};
</script>

<style scoped lang="scss">
.project-list {
	margin-bottom: 20px;
	padding: 8px;
	padding-bottom: 30px;
}

.project-icon {
	height: 20px;
	width: 4px;
	background: var(--primary-color);
	position: absolute;
	left: -10px;
	top: 0;
}

.project-item {
	background-color: #ffffff;
	border-radius: 10px;
	margin-bottom: 10px;
	overflow: hidden;
}

.project-header {
	display: flex;
	padding: 15px;
	align-items: center;
	border-bottom: 1px solid #eee;
	background: #ebeffd;
}

.project-info {
	flex: 1;
}

.project-title {
	font-size: 18px;
	font-weight: bold;
	margin-bottom: 5px;
	position: relative;
	display: flex;
	align-items: center;
	gap: 8px;
}

.project-code,
.project-indicators {
	font-size: 14px;
	color: #666;
	margin-bottom: 3px;
}

.project-status {
	min-width: 80px;
	text-align: center;
}

.status-button {
	background: var(--primary-color);
	color: #ffffff;
	font-size: 14px;
	padding: 4px 8px;
	border-radius: 4px;
}

.detail-panel {
	padding: 3px;
	padding-top: 0;

	.detail-group {
		padding: 12px;
		border-bottom: 1px solid #eee;
	}
}

.detail-title {
	font-weight: bold;
	margin-bottom: 10px;
	display: flex;
	align-items: center;

	.header-index {
		height: 20px;
		width: 20px;
		border-radius: 50%;
		background: #405ee0;
		color: #ffffff;
		margin-right: 8px;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 12px;
	}
}

.detail-row {
	margin-bottom: 10px;
	color: #666;
	display: flex;
	flex-wrap: wrap;
	gap: 12px;

	.detail-row-item {
		min-width: 45%;
	}
}

.item-value {
	background: #f2f2f2;
	padding: 8px 12px;
	border-radius: 4px;
}

.input-group {
	margin: 15px 0;
	display: flex;
	align-items: center;

	.label {
		width: 100px;
		font-weight: bold;
	}

	input {
		flex: 1;
		height: 40px;
		padding: 0 10px;
		border: 1px solid #ddd;
		border-radius: 5px;
	}
}

.photo-upload {
	display: flex;
	align-items: center;
	margin-bottom: 6px;

	.label {
		width: 100px;
		font-weight: bold;
	}

	.value {
		display: flex;
		align-items: center;
	}
}

.mid-content {
	display: flex;
	justify-content: space-between;
	padding: 0 16rpx;
	padding-top: 12px;

	.left {
		display: flex;
		font-weight: 600;
		> view:first-child {
			margin-right: 16px;
		}
	}
}

.excetImage {
	width: 100px;
	height: 100px;
}
</style>
